﻿using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
//using Microsoft.VisualBasic.FileIO;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;
using System.Text.Json.Serialization;
using log4net.Repository.Hierarchy;
using System.Xml;
using System.Xml.Linq;

namespace XmlEditor.ViewModel
{
    public class MainViewModel : ObservableObject
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        //private string xmlFile;
        public MainViewModel()
        {
            log.Debug("MainViewModel ctor");
            this.Rate = 2.0;

            string[] xmlFiles = Directory.GetFiles(Environment.CurrentDirectory, "*.xml");
            if (xmlFiles.Any())
            {
                this.XmlFileName = xmlFiles[0];
            }
            else
            {
                this.Message = "未在exe旁边找到任何xml文件";
            }

        }



        private string xmlFileName;
        public string XmlFileName
        {
            get => xmlFileName;
            set => SetProperty(ref xmlFileName, value);
        }


        private double rate;
        public double Rate
        {
            get => rate;
            set => SetProperty(ref rate, value);
        }


        private string message;
        public string Message
        {
            get => message;
            set => SetProperty(ref message, value);
        }


        private bool isSearchAndReplacing;
        private RelayCommand searchAndReplaceCommand;

        public RelayCommand SearchAndReplaceCommand
        {
            get
            {
                return searchAndReplaceCommand
                  ?? (searchAndReplaceCommand = new RelayCommand(
                    async () =>
                    {
                        if (isSearchAndReplacing)
                        {
                            return;
                        }

                        isSearchAndReplacing = true;
                        SearchAndReplaceCommand.NotifyCanExecuteChanged();

                        await SearchAndReplace();

                        isSearchAndReplacing = false;
                        SearchAndReplaceCommand.NotifyCanExecuteChanged();
                    },
                    () => !isSearchAndReplacing));
            }
        }
        private async Task SearchAndReplace()
        {
            await Task.Run(() =>
            {
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                XDocument xDoc = XDocument.Parse(File.ReadAllText(this.XmlFileName, Encoding.GetEncoding("GB2312")));
                var query = from c in xDoc.Elements("table").Elements("row")
                            select c;
                foreach (XElement book in query)
                {
                    foreach (var at in book.Attributes())
                    {
                        string name = at.Name.ToString();
                        Console.WriteLine(name);
                        if (name.Contains("最") || name.Contains("增加"))
                        {
                            string old = book.Attribute(name).Value;
                            int targetValue = (int)Math.Ceiling(Convert.ToSingle(old) * this.Rate);
                            book.Attribute(name).Value = targetValue.ToString();
                        }
                    }
                }
                xDoc.Save(this.XmlFileName);
                this.Message = "完成文件替换";
            });
        }




    }
}
